# -*- coding: utf-8 -*-
from flask_wtf import Form
from wtforms import StringField, BooleanField, PasswordField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
from models import User
from app import app

__author__ = 'nibo'


class LoginForm(Form):
    """
    用户登录表单
    """
    email = StringField(u'邮箱：', validators=[DataRequired(u'邮箱不能为空！')])
    password = PasswordField(u'密码：', validators=[DataRequired(u'密码不能为空！')])
    remember_me = BooleanField(u'记住我', default=False)


class SignInForm(Form):
    """
    用户注册表单
    """
    nickname = StringField(u'昵称：', validators=[DataRequired(u'昵称不能为空！')])
    email = StringField(u'邮箱：', validators=[
        DataRequired(u'邮箱不能为空！'),
        Email(u'邮箱格式不正确！')
    ])
    password = PasswordField(u'密码：', validators=[
        DataRequired(u'密码不能为空！'),
        Length(min=6, max=16, message=u'密码长度为6~16位！')
    ])
    confirm_password = PasswordField(u'确认密码：')

    def validate(self):
        if not Form.validate(self):
            return False
        if self.password.data != self.confirm_password.data:
            self.confirm_password.errors.append(u'两次输入的密码不一致！')
            return False
        u = User.query.filter_by(nickname=self.nickname.data).first()
        if u is not None:
            self.nickname.errors.append(u'昵称已存在，请重新输入！')
            return False
        u = User.query.filter_by(email=self.email.data).first()
        if u is not None:
            self.email.errors.append(u'邮箱地址已存在，请重新输入！')
            return False
        return True


class EditUserForm(Form):
    """
    编辑用户信息表单
    """
    nickname = StringField(u'昵称：', validators=[DataRequired(u'昵称不能为空！')])
    about_me = TextAreaField(u'个人介绍：',
                             validators=[Length(min=0, max=140, message=u'长度不能超过140个字符')])

    def __init__(self, original_nickname, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)
        self.original_nickname = original_nickname

    def validate(self):
        if not Form.validate(self):
            return False
        if self.original_nickname == self.nickname.data:
            return True
        user = User.query.filter_by(nickname=self.nickname.data).first()
        app.logger.debug(u'用户信息：%s' % user)
        if user is not None:
            self.nickname.errors.append(u'昵称已存在，请重新修改！')
            return False
        return True


class PostForm(Form):
    """
    发布微博表单
    """
    post = TextAreaField(u'发布微博：', validators=[
        DataRequired(u'微博信息不能为空！'),
        Length(max=140, message=u'微博长度不能超过140个字符！')
    ])


class SearchForm(Form):
    """
    搜索表单
    """
    search = StringField(u'搜索：', validators=[DataRequired(u'请输入搜索关键字！')])
